package com.legna.mhxy.support.controller;

import com.legna.mhxy.support.entity.RingTask;
import com.legna.mhxy.support.entity.TaskProfit;
import com.legna.mhxy.support.service.TaskService;
import com.legna.mhxy.support.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;


@Tag(name="环任务")
@RestController
@RequestMapping("/task")
@AllArgsConstructor
public class TaskController {

    private final TaskService taskService;

    @PostMapping
    @Operation(summary = "新增")
    public Result<String> save(@RequestParam("userId") Long userId,
                               @RequestParam("name") String name,
                               @RequestParam("type") Integer type) {
        RingTask ringTask = new RingTask();
        if (StringUtils.isBlank(name)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
            name = ((type == 1?"人环":"宠环") + sdf.format(new Date()));
        }
        ringTask.setName(name);
        ringTask.setUserId(userId);
        ringTask.setType(type);
        ringTask.setStatus(1);
        taskService.createTask(ringTask);
        return Result.ok();
    }
    @PutMapping("/cost/add")
    @Operation(summary = "结束")
    public Result<String> addCost(@RequestParam("taskId") Long taskId,@RequestParam("cost") Double cost) {
        taskService.addCost(taskId,cost);
        return Result.ok();
    }
    @PutMapping
    @Operation(summary = "结束")
    public Result<String> finish(@RequestParam("taskId") Long taskId) {
        taskService.finishTask(taskId);
        return Result.ok();
    }
    @GetMapping
    @Operation(summary = "根据用户查询")
    public Result<RingTask> getByUserId(@RequestParam("userId") Long userId) {
        RingTask ringTask = taskService.getByUserId(userId);
        return Result.ok(ringTask);
    }

    @PostMapping("profit")
    @Operation(summary = "新增收益")
    public Result<String> addProfit(@RequestParam("taskId") Long taskId,
                                    @RequestParam("type") Integer type,
                                    @RequestParam(value = "categoryId",required = false) Long categoryId,
                                    @RequestParam(value = "worth",required = false) Double worth,
                                    @RequestParam(value = "grade",required = false) Integer grade) {
        if (worth == 0d){
            worth = null;
        }
        TaskProfit taskProfit = new TaskProfit();
        taskProfit.setTaskId(taskId);
        taskProfit.setWorth(worth);
        taskProfit.setCategoryId(categoryId);
        taskProfit.setGrade(grade);
        taskProfit.setType(type);
        taskService.addProfit(taskProfit);
        return Result.ok();
    }
}
